import Vue from 'vue'
import Vuex from 'vuex'
import storage from '../utils/storage'
import { signInPwd,logout ,getUserInfo} from "@/api/index.js"
Vue.use(Vuex);
const store = new Vuex.Store({
	// 属性值
	state: {
		users:'',
		token:"",
		user:storage.getJson("users")
	},
	// 对外方问state属性内容
	getters: {
		getCart: state => {
			let users = storage.getJson("users");
			if (users == null) {
				return 0;
			}

			return users.shop_count;
		}
	},
	// Mutation 必须是同步函数
	// 更改state属性内容
	// 使用：this.$store.commit("setUserInfo",{  });
	mutations: {
		UPDATEUSERS_YG(state, data){
			state.users = data;
		},
		UPDATEUSERS(state, data) {
			state.users = data;
			console.log(data)
			storage.setJson("users", data);
		},
		DELETEUSERS(state, name) {
			state.users = null;
			storage.remove(name);
		},
		UPDATECART(state, data) {
			state.users.shop_count = data;
			let users = storage.getJson("users");
			users.shop_count = data;
			storage.setJson("users", users);
		},
		SET_TOKEN(state, data){
			storage.set('token',data)
		},
		REMOVE_TOKEN(state, data){
			storage.remove('token')
		}
	},
	// Action 可以包含任意异步操作
	// 通过 context.commit 可以方问mutations方法
	// 也可以获得getters内容
	// 通过 this.$store.dispatch("getUser") 来取得内容
	actions: {
		login(context,userInfo) {
		    return new Promise((resolve, reject) => {
		      signInPwd(userInfo).then(res => {
				  console.log(res)
		        if (res.code == 200) {
				  storage.set('token',res.data.token)
				  context.commit('SET_TOKEN', res.data.token)
		          resolve(res)
		          // console.log(data)
		        }else{
					uni.showToast({
						icon: 'none',
						title: res.msg
					})
				}
		      })
		    })
		},
		getInfo(context){
			return new Promise((resolve, reject) => {
			  getUserInfo().then(res => {
			    if (res.code == 200) {  
				  context.commit('UPDATEUSERS', res.data)
			      resolve(res)
			      // console.log(data)
			    }
			  })
			})
		},
		gout(context) {
			return new Promise(function(resolve, reject) {
				// logout().then(res => {
				  // if (res.code == 200) {	
					  context.commit('REMOVE_TOKEN')
					  context.commit('DELETEUSERS','users')
						uni.reLaunch({
							url:"/pages/login"
						});	
				  // }
				// })
			});
		},
		gout_yg(context){
			return new Promise(function(resolve, reject) {
				context.commit('DELETEUSERS','users_yg')
				uni.reLaunch({
					url:"/pages/mine/index"
				});	
			});
		}
	}
})

export default store
